<template>
  <div class="map_container" ref="mapRef"></div>
  <!-- 图例 -->
  <div id="legend">
    <h4>图例</h4>
    <ul>
      <li><img :src="greenMarker" alt="Green Marker"> 一级保护(树龄&gt;500年)</li>
      <li><img :src="blueMarker" alt="Blue Marker"> 二级保护(300&lt;树龄&lt;=500年)</li>
      <li><img :src="yellowMarker" alt="Yellow Marker"> 三级保护(树龄&lt;=500年)</li>
      <li><img :src="redMarker" alt="Red Marker"> 异常</li>
    </ul>
  </div>
  <!-- 行政区划面板 -->
  <div id="panel">
    <h4>下属行政区查询</h4>
    <div class="input-item">
      <div class="title">省市区</div>
      <select v-model="selectedProvince" @change="search('province')">
        <option value="">---请选择---</option>
        <option v-for="(item, index) in provinceList" :key="index" :value="index">{{ item.fullname }}</option>
      </select>
    </div>
    <div class="input-item">
      <div class="title">地级市</div>
      <select v-model="selectedCity" @change="search('city')">
        <option value="">---请选择---</option>
        <option v-for="(item, index) in cityList" :key="index" :value="index">{{ item.fullname }}</option>
      </select>
    </div>
    <div class="input-item">
      <div class="title">区县</div>
      <select v-model="selectedDistrict" @change="search('district')">
        <option value="">---请选择---</option>
        <option v-for="(item, index) in districtList" :key="index" :value="index">{{ item.fullname }}</option>
      </select>
    </div>
  </div>

  <!-- 统计图 -->
  <div id="charts-container">
    <h4>统计信息</h4>
    <div style="display: flex; flex-wrap: wrap; gap: 20px;">
      <!-- 科名分析图表 -->
      <div style="flex: 1; min-width: 300px;">
        <div ref="familyChartRef" style="width: 100%; height: 250px;"></div>
      </div>

      <!-- 属名分析图表 -->
      <div style="flex: 1; min-width: 300px;">
        <div ref="genusChartRef" style="width: 100%; height: 250px;"></div>
      </div>

      <!-- 保护等级分析图表 -->
      <div style="flex: 1; min-width: 300px;">
        <div ref="protectionChartRef" style="width: 100%; height: 250px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { getMarkersByRegion, getTreeDetailsById, getTreeStatistics } from '@/apis/treeAPI';
import { ElMessage } from 'element-plus';
import greenMarker from '@/assets/images/markerIcon/green.png';
import blueMarker from '@/assets/images/markerIcon/blue.png';
import yellowMarker from '@/assets/images/markerIcon/yellow.png';
import redMarker from '@/assets/images/markerIcon/red.png';
import router from '@/router';
// 引入 echarts 库
import * as echarts from 'echarts'

// 地图容器的 DOM 引用
const mapRef = ref(null);
let map = null; // 地图实例
let polygons = null; // 多边形图层，用于绘制行政区边界
let markerLayer; // 全局变量
let infoWindow = null;//信息窗口

// 获取腾讯地图 API 的命名空间对象
const TMap = window.TMap;

// 省市区下拉列表数据
const provinceList = ref([]); // 省级列表
const cityList = ref([]);    // 市级列表
const districtList = ref([]); // 区级列表

// 当前选中的值
const selectedProvince = ref(''); // 当前选择的省索引
const selectedCity = ref('');     // 当前选择的市索引
const selectedDistrict = ref(''); // 当前选择的区索引

// 创建行政区划查询服务实例，返回包含边界坐标的区域数据
const districtService = new TMap.service.District({ polygon: 2 });

// 页面挂载后初始化地图和加载省级,标记点数据
onMounted(() => {
  initMap();
  loadProvinces();
});

// 初始化地图配置
function initMap() {
  const center = new TMap.LatLng(40, 116); // 设置地图中心点（经纬度）
  map = new TMap.Map(mapRef.value, {
    zoom: 8,
    center,
  });

  markerLayer = new TMap.MultiMarker({
    map: map,
    styles: styles, // 使用上面定义的 styles
    geometries: []
  });
  // 初始化 InfoWindow
  infoWindow = new TMap.InfoWindow({
    map: map, // 必须绑定地图实例
    position: map.getCenter(), // 初始位置设为地图中心点
    offset: { x: 0, y: -32 }, // 偏移量，让信息窗显示在标记上方
  });
  infoWindow.close();//初始关闭信息窗关闭

  // 添加点击事件监听
  markerLayer.on('click', (event) => {
    const clickedId = event.geometry.id;
    infoWindow.open(); //打开信息窗
    getTreeDetails(clickedId); // 获取并显示古树详情
  });

  // 初始化多边形图层，用于绘制行政区边界
  polygons = new TMap.MultiPolygon({
    map: map,
    geometries: [],
  });

  // 初始化图表
  nextTick(() => {
    updateCharts();
  });
}

// 加载全国省份数据，默认选中云南省并加载其下属城市
function loadProvinces() {
  districtService.getChildren().then((result) => {
    provinceList.value = result.result[0]; // 存储省份列表
    cityList.value = [];
    districtList.value = [];

    // 查找"云南省"的索引
    const yunnanIndex = provinceList.value.findIndex(province => province.fullname === '云南省');

    if (yunnanIndex !== -1) {
      selectedProvince.value = yunnanIndex; // 默认选中云南省
      const province = provinceList.value[yunnanIndex];
      // 获取云南省下属的地级市
      districtService.getChildren({ id: province.id }).then((res) => {
        cityList.value = res.result[0] || [];
        drawPolygon(province.id, province.polygon); // 绘制云南省边界
      });
      fetchMarkersByRegion('province', province.id);
    }
  });
}

// 根据用户选择的层级加载下一级数据
function search(level) {
  if (level === 'province' && selectedProvince.value !== '') {
    const province = provinceList.value[selectedProvince.value];
    cityList.value = [];
    districtList.value = [];

    // 获取该省下属地级市
    districtService.getChildren({ id: province.id }).then((res) => {
      cityList.value = res.result[0] || [];
      drawPolygon(province.id, province.polygon); // 绘制省界
    });
    // 请求省级标记点数据
    fetchMarkersByRegion('province', province.id);
  } else if (level === 'city') {
    if (selectedCity.value === '') {
      // 用户选择了"请选择"，恢复省级边界
      if (selectedProvince.value !== '') {
        const province = provinceList.value[selectedProvince.value];
        drawPolygon(province.id, province.polygon);
        fetchMarkersByRegion('province', province.id);
      }
      districtList.value = [];
    } else {
      const city = cityList.value[selectedCity.value];
      districtList.value = [];

      districtService.getChildren({ id: city.id }).then((res) => {
        // 如果子项 ID 长度大于6，表示是街道级别
        if (res.result[0].length > 0 && res.result[0][0].id.length > 6) {
          drawPolygon(city.id, city.polygon); // 绘制市界
        } else {
          districtList.value = res.result[0] || [];
          drawPolygon(city.id, city.polygon); // 绘制市界
        }
      });
      // 请求市级标记点数据
      fetchMarkersByRegion('city', city.id);
    }
  } else if (level === 'district' && selectedDistrict.value !== '') {
    const district = districtList.value[selectedDistrict.value];

    districtService.getChildren({ id: district.id }).then((res) => {
      drawPolygon(district.id, district.polygon); // 绘制区界
    });
    fetchMarkersByRegion('district', district.id);
  }
}

// 绘制指定地区的多边形边界
function drawPolygon(placeId, polygonArray) {
  // 清除已有图形
  polygons.remove(polygons.getGeometries().map((item) => item.id));

  let boundsList = [];
  const newGeometries = polygonArray.map((polygon, index) => {
    boundsList.push(fitBounds(polygon)); // 计算每个多边形的边界范围
    return {
      id: `${placeId}_${index}`, // 图形唯一标识
      paths: polygon,            // 多边形路径坐标数组
    };
  });

  // 合并所有边界范围为一个整体范围
  boundsList = boundsList.reduce((a, b) =>
    fitBounds([a.getNorthEast(), a.getSouthWest(), b.getNorthEast(), b.getSouthWest()])
  );

  polygons.updateGeometries(newGeometries); // 更新地图上的多边形
  map.fitBounds(boundsList);                // 自动调整地图视野以适应区域
}

// 计算给定坐标点集合的包围矩形（LatLngBounds）
function fitBounds(latLngList) {
  if (latLngList.length === 0) return null;

  let boundsN = latLngList[0].getLat();
  let boundsS = boundsN;
  let boundsW = latLngList[0].getLng();
  let boundsE = boundsW;

  latLngList.forEach((point) => {
    boundsN = Math.max(boundsN, point.getLat());
    boundsS = Math.min(boundsS, point.getLat());
    boundsE = Math.max(boundsE, point.getLng());
    boundsW = Math.min(boundsW, point.getLng());
  });

  return new TMap.LatLngBounds(new TMap.LatLng(boundsS, boundsW), new TMap.LatLng(boundsN, boundsE));
}

const styles = {
  "green": new TMap.MarkerStyle({
    width: 25,
    height: 35,
    src: greenMarker,
  }),
  "blue": new TMap.MarkerStyle({
    width: 25,
    height: 35,
    src: blueMarker,
  }),
  "yellow": new TMap.MarkerStyle({
    width: 25,
    height: 35,
    src: yellowMarker,
  }),
  "red": new TMap.MarkerStyle({
    width: 25,
    height: 35,
    src: redMarker,
  }),
};

function addMarkers(dataArray) {
  const markers = dataArray.map(data => {
    let styleId = 'red'; // 默认样式

    if (data.status === 1) {
      if (data.protectionLevel === 1) {
        styleId = 'green';
      } else if (data.protectionLevel === 2) {
        styleId = 'blue';
      } else if (data.protectionLevel === 3) {
        styleId = 'yellow';
      }
    } else {
      styleId = 'red'
    }

    return {
      id: data.treeId, // 假设后端返回唯一标识符
      styleId: styleId,
      position: new TMap.LatLng(data.gpsLatitude, data.gpsLongitude),
    };
  });

  markerLayer.updateGeometries(markers); // 更新标记图层
}

async function fetchMarkersByRegion(level, code) {
  try {
    if (markerLayer) {
      markerLayer.setGeometries([]);
    }
    const result = await getMarkersByRegion(level, code);
    if (result.code === 1 && Array.isArray(result.data)) {
      addMarkers(result.data); // 添加标记点
      // 更新图表数据
      updateCharts();
    } else {
      ElMessage.error(result.msg || `获取${level}标记点失败`);
    }
  } catch (error) {
    console.error('请求失败:', error);
  }
}

async function getTreeDetails(treeId) {
  try {
    const result = await getTreeDetailsById(treeId); // 调用接口获取古树详情
    if (result.data && result.code === 1) {
      const treeData = result.data;

      const marker = markerLayer.getGeometryById(treeId);
      const position = marker ? marker.position : map.getCenter();
      showTreeInfo(treeData, position);
    } else {
      ElMessage.error(result.msg || '获取古树详情失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络异常，请稍后再试');
  }
}

function showTreeInfo(treeData, position) {
  const content = `
    <div style="display: flex; padding: 10px; width: 400px; box-sizing: border-box;">
      <!-- 左侧详情 -->
      <div style="flex: 1; display: flex; flex-direction: column; align-items: flex-start; justify-content: center; text-align: left;">
        <h4 style="margin: 0 0 10px 0; font-size: 16px;">古树详情</h4>
        <p style="margin: 0 0 8px 0; font-size: 14px;"><strong>名称：</strong>${treeData.chineseName || '未知'}</p>
        <p style="margin: 0 0 8px 0; font-size: 14px;"><strong>编号：</strong>${treeData.treeId || '未知'}</p>
        <p style="margin: 0 0 8px 0; font-size: 14px;"><strong>保护等级：</strong>
          <el-tag size="small">
            ${getProtectionLevelText(treeData.protectionLevel)}
          </el-tag>
        </p>
        <p style="margin: 0 0 8px 0; font-size: 14px; line-height: 1.4;">
          <strong>位置：</strong><span>${treeData.locationAddress || '未知'}</span>
        </p>
        <p style="margin: 0 0 8px 0; font-size: 14px;"><strong>树龄：</strong>${treeData.estimatedAge || '未知'} 年</p>
        <p style="margin: 0 0 8px 0; font-size: 14px;"><strong>状态：</strong>${treeData.status || '未知'}</p>
      </div>

      <!-- 右侧图片 -->
      <div style="flex: 1; display: flex; align-items: center; justify-content: center; margin-left: 10px;">
        <img 
          src="${treeData.mediaList?.[0]?.mediaUrl || 'https://via.placeholder.com/100x120?text=暂无图片'}" 
          alt="古树图片" 
          style="width: 130px; height: 120px; object-fit: contain; background-color: white;">
      </div>
    </div>
   <button id="detail-btn-${treeData.treeId}" style="margin-top: 10px; padding: 6px 12px; background-color: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">
      点击查看更多详情
    </button>
  `;

  
  infoWindow.setContent(content);
  infoWindow.setPosition(position);
  infoWindow.open();
  // 使用 setTimeout 确保 DOM 更新后再添加事件监听器
  setTimeout(() => {
    const button = document.getElementById(`detail-btn-${treeData.treeId}`);
    if (button) {
      button.addEventListener('click', () => {
        // 使用 Vue Router 跳转到详细信息页面
        router.push(`/treeDetail/${treeData.treeId}`);
      });
    }
  }, 0);
}

// 辅助函数：返回保护等级中文
function getProtectionLevelText(level) {
  switch (level) {
    case 1: return '一级';
    case 2: return '二级';
    case 3: return '三级';
    default: return '未定级';
  }
}

onBeforeUnmount(() => {
  if (map) {
    map.destroy(); // 调用地图库的销毁方法
    map = null;
  }
});

// 图表引用
const familyChartRef = ref(null);
const genusChartRef = ref(null);
const protectionChartRef = ref(null);

// 图表实例
let familyChartInstance = null;
let genusChartInstance = null;
let protectionChartInstance = null;

// 初始化科名分析图表
const initFamilyChart = (chartData) => {
  if (familyChartRef.value) {
    if (familyChartInstance) {
      familyChartInstance.dispose();
    }
    familyChartInstance = echarts.init(familyChartRef.value);

    const familyOption = {
      title: {
        text: '科名分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '15%',
        left: 'center'
      },
      series: [
        {
          name: '科名比例',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['50%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'center',

            formatter: '{d}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.familyData || [] // 使用后端数据
        }
      ]
    };

    familyChartInstance.setOption(familyOption);
  }
};

/* 修改属名分析图表配置  */
const initGenusChart = (chartData) => {
  if (genusChartRef.value) {
    if (genusChartInstance) {
      genusChartInstance.dispose();
    }
    genusChartInstance = echarts.init(genusChartRef.value);

    const genusOption = {
      title: {
        text: '属名分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '15%',
        left: 'center'
      },
      series: [
        {
          name: '属名比例',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['50%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'center',
            formatter: '{d}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.genusData || [] // 使用后端数据
        }
      ]
    };

    genusChartInstance.setOption(genusOption);
  }
};

/* 修改保护等级分析图表配置 */
const initProtectionChart = (chartData) => {
  if (protectionChartRef.value) {
    if (protectionChartInstance) {
      protectionChartInstance.dispose();
    }
    protectionChartInstance = echarts.init(protectionChartRef.value);

    const protectionOption = {
      title: {
        text: '保护等级分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '15%',
        left: 'center'
      },
      series: [
        {
          name: '保护等级',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['50%', '60%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'center',

            formatter: '{d}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData.protectionData || [] // 使用后端数据
        }
      ]
    };

    protectionChartInstance.setOption(protectionOption);
  }
};

// 新增：专门用于更新图表的函数
const updateCharts = async () => {
  const chartData = await fetchChartData();
  if (chartData) {
    initFamilyChart(chartData);
    initGenusChart(chartData);
    initProtectionChart(chartData);
  }
};

// 数据转换函数
const transformChartData = (rawData, nameField) => {
  if (!rawData || !Array.isArray(rawData)) {
    return [];
  }

  return rawData.map(item => ({
    name: item[nameField],  // familyName 或 genusName 等
    value: item.count       // 数量
  }));
};

// 保护等级转换函数
const transformProtectionLevelData = (rawData) => {
  if (!rawData || !Array.isArray(rawData)) {
    return [];
  }

  // 保护等级映射
  const protectionLevelMap = {
    1: '一级保护',
    2: '二级保护',
    3: '三级保护'
  };

  return rawData.map(item => ({
    name: protectionLevelMap[item.protectionLevel] || `未知等级(${item.protectionLevel})`,
    value: item.count
  }));
};

// 获取图表数据（根据当前选择的行政区划）
const fetchChartData = async () => {
  try {
    // 根据当前选中的行政区划获取对应数据
    let regionCode = '';
    let level = '';

    if (selectedDistrict.value !== '') {
      regionCode = districtList.value[selectedDistrict.value].id;
      level = 'district';
    } else if (selectedCity.value !== '') {
      regionCode = cityList.value[selectedCity.value].id;
      level = 'city';
    } else if (selectedProvince.value !== '') {
      regionCode = provinceList.value[selectedProvince.value].id;
      level = 'province';
    } else {
      // 默认加载全国数据
      level = 'province';
    }

    const result = await getTreeStatistics(level, regionCode); // 传入区域级别和代码
    if (result.code === 1) {
      const rawData = result.data;

      // 转换数据格式
      return {
        familyData: transformChartData(rawData.familyCountList, 'familyName'),
        genusData: transformChartData(rawData.genusCountList, 'genusName'),
        protectionData: transformProtectionLevelData(rawData.protectionCountList)
      };
    } else {
      ElMessage.error(result.msg || '获取统计数据失败');
      return null;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('网络异常，请稍后再试');
    return null;
  }
};

// 窗口大小变化时调整图表尺寸
const resizeCharts = () => {
  familyChartInstance?.resize();
  genusChartInstance?.resize();
  protectionChartInstance?.resize();
}

// 组件挂载后执行初始化
onMounted(() => {
  // 监听窗口大小变化事件以支持响应式
  window.addEventListener('resize', resizeCharts)
})

// 组件卸载前清理资源，防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  familyChartInstance?.dispose();
  genusChartInstance?.dispose();
  protectionChartInstance?.dispose();
})
</script>

<style scoped>
.map_container {
  height: 100vh;
  width: 100%;
  position: relative;
}

#panel {
  position: absolute;
  background: #fff;
  width: 350px;
  padding: 20px;
  z-index: 9999;
  top: 90px;
  left: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.input-item {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
}

.title {
  width: 60px;
  text-align: justify;
  display: inline-block;
  text-align-last: justify;
}

select {
  width: 200px;
  padding: 5px;
}

.info-image {
  flex: 0 0 110px;
  /* 固定宽度，防止伸缩影响布局 */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 15px;
}

#legend {
  position: absolute;
  bottom: 30px;
  /* 距离底部 */
  left: 30px;
  /* 距离左侧 */
  background: white;
  padding: 10px;
  z-index: 9999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 240px;
}

#legend h4 {
  margin-top: 0;
  font-size: 16px;
}

#legend ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#legend li {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

#legend img {
  width: 20px;
  height: 30px;
  margin-right: 10px;
}

#charts-container {
  position: absolute;
  top: 90px;
  right: 30px;
  width: 500px;
  background: rgba(255, 255, 255, 0.2);
  /* 添加透明背景 */
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;
  backdrop-filter: blur(5px);
  /* 添加模糊效果 */
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}
</style>